import { Tools } from "../../common/Tools";
import { AudioManager1 } from "../../manager/AudioManager1";
import { EventManager } from "../../manager/EventManager";
import { LvItemInfo_15 } from "../../model/OtherModel";
import TouchScale from "../../item/Common/TouchScale";
import LvItem from "../../LvItem";
import LevelPre_15 from "./LevelPre_15";
const { ccclass, property } = cc._decorator;
import { BUNDLE_TYPE_ENUM, EVENT_NAME_ENUM } from "../../base/EnumIndex";

@ccclass
export default class LvItem_15 extends cc.Component {
    /** 是否可点击  Bool */
    isClick: boolean = false;
    /** 配置信息 */
    config: LvItemInfo_15 = null;
    /** 关卡总类 */
    levelBase: LevelPre_15 = null;

    stateIndex: number = 0;      //当前的状态index
    initPos: cc.Vec3 = null;    //初始化坐标
    initSibIndex: number = 0;    //初始化时候得层级

    /** 自动移动镜头的方向 */
    autoMove_X: number = 0;
    autoMove_Y: number = 0;
    onLoad() {
        this.initPos = cc.v3(this.node.position);
        this.initSibIndex = this.node.getSiblingIndex();

        // if (!this.node.getComponent(cc.BlockInputEvents)) {
        //     this.node.addComponent(cc.BlockInputEvents);
        // }
    }
    // start () {
    // }
    update(dt: number): void {
        if (this.autoMove_X == 0 && this.autoMove_Y == 0) {
            return;
        }
        let moveX = this.autoMove_X * dt;
        let moveY = this.autoMove_Y * dt;
        let tempPos = cc.v3(this.levelBase.huaNode.position);
        this.levelBase.huaNode.getComponent(TouchScale).setResictPos(moveX, moveY);

        if (tempPos.x == this.levelBase.huaNode.x) {
            moveX = 0;
        } if (tempPos.y == this.levelBase.huaNode.y) {
            moveY = 0;
        }
        // let moveScale = this.node.scale / this.getWorldScale(this.node.scale, this.node);
        // this.node.position = this.node.position.add(cc.v3(-moveX, -moveY));//.multiplyScalar(moveScale)
        this.node.setPosition(this.node.position.x - moveX, this.node.position.y - moveY)
        // cc.log("边缘移动x：", this.node.position.x)
    }
    touchStartPos: cc.Vec3 = null;
    isTouchMove: boolean = false;
    initItem(config: any, levelBase: LevelPre_15) {
        this.config = config;
        this.levelBase = levelBase;

        this.node.on(cc.Node.EventType.TOUCH_START, this.touchStartBack, this);
        if (this.configIsTouchMove) {
            this.node.on(cc.Node.EventType.TOUCH_MOVE, this.touchMoveBack, this);
        }
        this.node.on(cc.Node.EventType.TOUCH_END, this.touchMoveEndBack, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.touchMoveEndBack, this);

        this.isClick = true;
    }
    /** 触摸开始回调 */
    touchStartBack(touches: cc.Event.EventTouch) {
        if (!this.isClick) { return; }
        this.touchStartPos = cc.v3(touches.getLocation());
        this.isTouchMove = false;
        this.node.zIndex = 1;
    };
    /** 触摸移动回调 */
    touchMoveBack(touches: cc.Event.EventTouch) {
        if (!this.isClick) { return; }
        if (this.config.interArr.length == 0) { return; }
        // if (!this.touchStartPos || Tools.getDistance(this.touchStartPos, touches.getLocation()) <= TOUCH_MOVE_LEN) { return; }
        this.isTouchMove = true;
        // this.levelBase.huaNode.getComponent(TouchScale).touchMoveCall(touches);

        /**
         * @date 2023/10/10修改
         */
        // let moveScale = this.node.scale / this.getWorldScale(this.node.scale, this.node);
        // this.node.position = this.node.position.add(cc.v3(touches.getDelta().multiplyScalar(moveScale)));
        let pos = Tools.getToNodePosForWorld(touches.getLocation(), this.node.parent);
        this.node.setPosition(pos);

        let tempPos = Tools.getToNodePosForNode(this.node, this.levelBase.huaNode.parent);
        let tempLen = 50;
        if (touches.getDelta().x > 0 && tempPos.x >= this.levelBase.huaNode.parent.width / 2 - this.node.width / 2 - tempLen) {
            this.autoMove_X = -800;
        } else if (touches.getDelta().x < 0 && tempPos.x <= -this.levelBase.huaNode.parent.width / 2 + this.node.width / 2 + tempLen) {
            this.autoMove_X = 800;
        } else if (touches.getDelta().y > 0 && tempPos.y >= this.levelBase.huaNode.parent.height / 2 - this.node.height / 2 - tempLen) {
            this.autoMove_Y = -800;
        } else if (touches.getDelta().y < 0 && tempPos.y <= -this.levelBase.huaNode.parent.height / 2 + this.node.height / 2 + tempLen) {
            this.autoMove_Y = 800;
        } else {
            this.autoMove_X = 0;
            this.autoMove_Y = 0;
        }

        this.runInterNode(true);
    }
    /** 触摸移动结束回调 */
    touchMoveEndBack(touches: cc.Event.EventTouch) {
        this.autoMove_X = 0;
        this.autoMove_Y = 0;
        if (!this.isClick) { return; }
        this.node.zIndex = 0;
        this.node.setSiblingIndex(this.initSibIndex);
        if (!this.isTouchMove && !this.clickConfig) {
            return;
        }
        this.runInterNode(false);
        AudioManager1.playAudio("game15_dianji", 1, BUNDLE_TYPE_ENUM.GAME)
    };
    /** 执行碰撞的检测    是都正在拖动中 */
    runInterNode(isMove: boolean = false) {
        let inter = this.getRunInterTween(isMove);
        if (!isMove && this.clickConfig) {
            inter = this.clickConfig;
        }
        if (inter) {
            if (inter.interTween) {
                if (typeof inter.interTween == "string") {
                    this.runJsonTween(inter.interTween);
                } else {
                    this.levelBase.runNodeTween(this.levelBase.viewBg, inter.interTween);
                }
            }
            if (inter.addState && inter.addState.length > 0) {
                let addArr = this.levelBase.addHaveStates(inter.addState);
                this.runStateTween(addArr);
                //播放正确音效
                if (this.levelBase.interJson.correctAudio) {
                    AudioManager1.playAudio("xuandui", 1, BUNDLE_TYPE_ENUM.GAME);
                }
            }
            if (inter.removeState) {
                let removeArr = this.levelBase.removeStates(inter.removeState);
                this.runStateTween(removeArr, "remove_");
            }
            // this.returnInitPos(false);
        } else if (!isMove) {
            if (this.levelBase.interJson.totalStep && this.config["isNotReturnInitPos"]) {
                EventManager.ins.emit(EVENT_NAME_ENUM.FINISH_INTER_TWEEN, "TcStep");
                if (this.levelBase.interJson.errorAudio) {
                    AudioManager1.playAudio("cuowu", 1, BUNDLE_TYPE_ENUM.GAME);
                }
            }
            if (this.levelBase.interJson.totalStep && this.config["cuowuJianNum"]) {
                EventManager.ins.emit(EVENT_NAME_ENUM.FINISH_INTER_TWEEN, "TcStep");
                if (this.levelBase.interJson.errorAudio) {
                    AudioManager1.playAudio("cuowu", 1, BUNDLE_TYPE_ENUM.GAME);
                }
            }
            if (this.levelBase.interJson.totalStep && this.config["fuhuo"]) {
                EventManager.ins.emit(EVENT_NAME_ENUM.FINISH_INTER_TWEEN, "costStep");
                if (this.levelBase.interJson.errorAudio) {
                    AudioManager1.playAudio("cuowu", 1, BUNDLE_TYPE_ENUM.GAME);
                }
                if (this.levelBase.interJson.errorLevelAudio) {
                    AudioManager1.stopAudioForName(this.levelBase.interJson.errorLevelAudio.resUrl);
                    AudioManager1.playAudio(this.levelBase.interJson.errorLevelAudio.resUrl, this.levelBase.interJson.errorLevelAudio.value, BUNDLE_TYPE_ENUM.LEVEL);
                }
            }
            this.returnInitPos();
        }
    };
    /** 获取要执行的交互Tween */
    getRunInterTween(isMove: boolean = false) {
        for (let i = 0; i < this.config.interArr.length; i++) {
            let tempData = this.config.interArr[i];
            let node = this.levelBase.getChildForName(isMove ? tempData.moveNode : tempData.interNode);
            if (!node) { continue; }
            if (this.isNodeInterNode(node, this.node) &&
                this.levelBase.isHaveStates(tempData.haveState)
                && this.levelBase.isHaveNoStates(tempData.haveNoState)) {
                return tempData;
            };
        }
        return null;
    };
    /** 返回原来的位置 */
    returnInitPos(isMove: boolean = true) {
        if (this.config["isNotReturnInitPos"] || this.config["fuhuo"]) {
            return;
        }
        let toPos = cc.v3(this.node.getComponent(LvItem).initPos);
        cc.tween(this.node).to(0.1, { position: toPos }).start();
    };
    /** 执行数组状态的Tween */
    runStateTween(states: Array<string>, tempStr: string = "add_") {
        for (let i = 0; i < states.length; i++) {
            this.runJsonTween(tempStr + states[i]);
        }
    };
    /** 执行某个Json配置的InterTween */
    runJsonTween(tweenName: string) {
        let tweenInfo = this.levelBase.getInterTwForName(tweenName);
        if (tweenInfo) {
            this.levelBase.runNodeTween(this.levelBase.viewBg, tweenInfo.interTween);
        }
    };
    /** 切换当前状态 */
    switchState(state?: number) {
        if (!this.config.allState) {
            return cc.log("没有配置allState:", this.node);
        }
        this.levelBase.removeStates([this.stateName]);

        if (state && this.config.allState.indexOf(state) >= 0) {
            this.stateIndex = this.config.allState.indexOf(state);
        } else {
            this.stateIndex++;
            if (this.stateIndex >= this.config.allState.length) {
                this.stateIndex = 0;
            }
        }

        let tweenInfo = this.levelBase.getInterTwForName(this.stateName);
        if (tweenInfo) {
            this.levelBase.runNodeTween(this.node, tweenInfo.interTween);
        }
        this.levelBase.addHaveStates([this.stateName]);
    };

    /** 判断两个节点是否相交 */
    isNodeInterNode(node1: cc.Node, node2: cc.Node) {
        if (!node1.active || !node2.active) { return false; };
        let wordPos1 = Tools.getToWorldPosAR(node1);
        let worldScale1 = this.getWorldScale(node1.scale, node1);
        let wordPos2 = Tools.getToWorldPosAR(node2);
        let worldScale2 = this.getWorldScale(node2.scale, node2);
        let size1 = cc.size(node1.width * worldScale1, node1.height * worldScale1);
        let size2 = cc.size(node2.width * worldScale2, node2.height * worldScale2);

        let rect1 = new cc.Rect(wordPos1.x - size1.width / 2, wordPos1.y - size1.height / 2, size1.width, size1.height);
        let rect2 = new cc.Rect(wordPos2.x - size2.width / 2, wordPos2.y - size2.height / 2, size2.width, size2.height);
        if (cc.Intersection.rectRect(rect1, rect2)) {
            return true;
        }
        return false;
    };
    /** 获取世界Scale */
    getWorldScale(tempScale: number = 1, node: cc.Node) {
        if (node.parent) {
            return this.getWorldScale(tempScale * node.parent.scale, node.parent);
        }
        return tempScale;
    };
    /** 本物品是否有 拖动事件 */
    get configIsTouchMove() {
        for (let i = 0; i < this.config.interArr.length; i++) {
            if (this.config.interArr[i].moveNode || this.config.interArr[i].interNode) {
                return true;
            }
        }
        return false;
    };
    /** 获取点击得Tween */
    get clickConfig() {
        for (let i = 0; i < this.config.interArr.length; i++) {
            let tempData = this.config.interArr[i];
            if (this.config.interArr[i].click && this.levelBase.isHaveStates(tempData.haveState)) {
                return this.config.interArr[i];
            }
        }
        return null;
    };


    get stateName() {
        return this.node.name + "_State_" + this.config.allState[this.stateIndex];
    }
}
